// fetch all featches URLs in parallel and reports their times and sizes

package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)
// go run fetchall.go http://www.suning.com http://www.suning.com
func main(){
	start := time.Now()
	// 创建一个接受 string 类型的通道
	ch := make(chan string)

	for _,url := range os.Args[1:] {
		go fetch(url, ch) // start a goroutime
	}

	for range os.Args[1:] {
		fmt.Println(<-ch) // receive from channel ch
	}

	fmt.Printf("%.2fs elapsed \n", time.Since(start).Seconds())

}

func fetch(url string,ch chan<- string) {
	start := time.Now()
	resp,err := http.Get(url)

	if err !=nil {
		ch <- fmt.Sprint(err)
		return
	}

	nbytes,err := io.Copy(ioutil.Discard,resp.Body)
	resp.Body.Close() // don't leak resources
	if err != nil {
		ch <- fmt.Sprintf("while reading %s : %v", url,err)
		return
	}

	secs := time.Since(start).Seconds()
	ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
}